<template>
  <div class="chart-detail">
    <div class="chart-detail-left">
      <!-- 左侧预览区域 -->
      <div class="chart-preview">
        <div class="chart-preview-header">
          <span class="chart-preview-title">预览效果</span>
          <div class="chart-tags">
            <span v-for="tag in chartData.tags" :key="tag" class="chart-tag">{{ tag }}</span>
          </div>
        </div>
        <div class="chart-preview-content" id="chart-container"></div>
      </div>
    </div>

    <!-- 右侧代码编辑区域 -->
    <div class="chart-code">
      <div class="chart-code-header">
        <span class="chart-code-title">配置代码</span>
        <div class="chart-code-actions">
          <template v-if="isAuthenticated">
            <button class="chart-run-btn" @click="runChart">运行</button>
            <button class="chart-run-btn" @click="copyCode">复制代码</button>
          </template>
        </div>
      </div>
      <div v-if="isAuthenticated" class="chart-code-content" id="monaco-editor"></div>
      <div v-else class="chart-code-login-required">
        <a-alert message="需要登录" description="请登录后查看和编辑代码" type="info" show-icon />
        <a-button type="primary" class="login-btn" @click="showLoginDialog"> 立即登录 </a-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import './index.css'
import { ref, onMounted, nextTick, onBeforeUnmount, watch } from 'vue'
import * as monaco from 'monaco-editor'
import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker'
import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker'
import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker'
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker'
import * as echarts from 'echarts'
import 'echarts-gl'
import 'echarts-liquidfill'
import 'echarts-wordcloud'
import $ from 'jquery'
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { getEchartsDetail } from '@/utils/api'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'

// 获取用户状态
const userStore = useUserStore()
const { isAuthenticated } = storeToRefs(userStore)

// 配置 Monaco Editor 的 Web Worker
self.MonacoEnvironment = {
  getWorker(_, label) {
    if (label === 'json') {
      return new jsonWorker()
    }
    if (label === 'css') {
      return new cssWorker()
    }
    if (label === 'html') {
      return new htmlWorker()
    }
    if (label === 'typescript' || label === 'javascript') {
      return new tsWorker()
    }
    return new editorWorker()
  }
}

const route = useRoute()
const chartData = ref({
  name: '',
  description: '',
  authorName: '',
  authorAvatar: '',
  tags: [],
  codeSnippet: '',
  type: ''
})

// Monaco Editor 实例
let editor = null
// ECharts 实例
let chart = null

// 初始化图表
const initChart = () => {
  const container = document.getElementById('chart-container')
  if (!container) return

  chart = echarts.init(container, null, {
    renderer: 'canvas',
    useDirtyRect: false
  })

  container.style.width = '100%'
  container.style.height = '100%'
  container.style.minHeight = '550px'
  container.style.minWidth = '524px'

  chart.resize()
}

// 初始化编辑器
const initEditor = (initialValue = '') => {
  const container = document.getElementById('monaco-editor')
  if (!container) return

  if (editor) {
    editor.dispose()
  }

  editor = monaco.editor.create(container, {
    value: initialValue,
    language: 'javascript',
    theme: 'vs-dark',
    automaticLayout: true,
    fontSize: 20,
    lineHeight: 22,
    minimap: {
      enabled: false
    },
    readOnly: false,
    fontFamily: 'Consolas, Monaco, monospace',
    fontWeight: '400',
    letterSpacing: 0.5,
    scrollBeyondLastLine: false
  })

  return editor
}

// 运行图表
const runChart = () => {
  if (!editor || !chart) return

  try {
    const code = editor.getValue()
    if (!code.trim()) return

    // 移除之前的错误监听器
    window._removeErrorListener?.()
    window._removeRejectionListener?.()

    // 添加错误处理
    const errorHandler = (event) => {
      if (event.error) {
        event.preventDefault()
      }
    }

    const rejectionHandler = (event) => {
      event.preventDefault()
    }

    window.addEventListener('error', errorHandler)
    window.addEventListener('unhandledrejection', rejectionHandler)

    window._removeErrorListener = () => window.removeEventListener('error', errorHandler)
    window._removeRejectionListener = () => window.removeEventListener('unhandledrejection', rejectionHandler)

    // 执行代码
    const fn = new Function(
      'echarts',
      'jQuery',
      'myChart',
      'nextTick',
      `
      const $ = jQuery;
      
      async function executeChart() {
        try {
          ${code}
          if (typeof option === 'undefined') {
            throw new Error('图表配置无效：option 未定义')
          }
          return option
        } catch (error) {
          throw error
        }
      }

      nextTick(async () => {
        try {
          const option = await executeChart()
          if (option) {
            nextTick(() => {
              myChart.setOption(option, true)
            })
          }
        } catch (error) {
          console.error(error)
        }
      })
    `
    )

    fn(echarts, $, chart, nextTick)
  } catch (error) {
    message.error('图表配置错误: ' + error.message)
  }
}

// 复制代码
const copyCode = () => {
  if (!editor) return
  const code = editor.getValue()
  if (!code.trim()) return

  navigator.clipboard
    .writeText(code)
    .then(() => {
      message.success('代码已复制到剪贴板')
    })
    .catch(() => {
      message.error('复制失败，请手动复制')
    })
}

// 显示登录对话框
const showLoginDialog = () => {
  // 触发全局事件以显示登录对话框
  window.dispatchEvent(new CustomEvent('openLogin'))
}

// 获取图表详情数据
const fetchChartDetail = async () => {
  try {
    const { id } = route.params
    if (!id) {
      throw new Error('图表ID不存在')
    }

    const response = await getEchartsDetail(id)

    if (response.code === 200 && response.data) {
      const detailData = response.data
      chartData.value = {
        name: detailData.name,
        description: detailData.description,
        authorName: '',
        authorAvatar: '',
        tags: detailData.tags || [],
        codeSnippet: detailData.codeSnippet,
        type: detailData.type
      }
      return detailData
    } else {
      throw new Error(response.msg || '获取图表详情失败')
    }
  } catch (error) {
    message.error('获取图表详情失败: ' + error.message)
  }
}

// 修改 initComponents 函数，分离预览和代码编辑的初始化
const initComponents = async () => {
  const data = await fetchChartDetail()
  if (!data) return

  // 初始化图表预览
  await nextTick()
  initChart()

  // 只有在用户已登录时才初始化编辑器
  if (isAuthenticated.value) {
    initEditor(data.codeSnippet)
    // 运行图表
    setTimeout(() => {
      runChart()
    }, 100)
  } else {
    // 未登录时，直接运行图表但不显示代码
    try {
      const fn = new Function(
        'echarts',
        'jQuery',
        'myChart',
        'nextTick',
        `
        const $ = jQuery;
        ${data.codeSnippet}
        if (typeof option !== 'undefined') {
          nextTick(() => {
            myChart.setOption(option, true)
          })
        }
        `
      )
      fn(echarts, $, chart, nextTick)
    } catch (error) {
      message.error('图表配置错误: ' + error.message)
    }
  }
}

// 监听认证状态变化
watch(isAuthenticated, (newValue) => {
  if (newValue) {
    // 用户登录后，初始化编辑器
    fetchChartDetail().then((data) => {
      if (data) {
        initEditor(data.codeSnippet)
      }
    })
  } else {
    // 用户登出后，销毁编辑器
    if (editor) {
      editor.dispose()
      editor = null
    }
  }
})

onMounted(() => {
  initComponents()
})

onBeforeUnmount(() => {
  window._removeErrorListener?.()
  window._removeRejectionListener?.()

  if (chart) {
    chart.dispose()
  }

  if (editor) {
    editor.dispose()
  }
})
</script>
